package com.visionblue.business.ship.page.orders

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.View
import androidx.core.content.ContextCompat
import com.jakewharton.disklrucache.DiskLruCache
import com.visionblue.business.ship.R
import com.visionblue.business.ship.base.BaseFragment
import com.visionblue.business.ship.util.MD5Util
import com.visionblue.business.ship.util.download.DownloadCallBack
import com.visionblue.business.ship.util.download.FileDownloader
import kotlinx.android.synthetic.main.frag_pdf_view.*
import razerdp.basepopup.BasePopupSDK.getApplication
import java.io.InputStream


/**
 * des:
 * author: tekabo
 * date: 2021/3/30
 */
open class PdfViewFragment:BaseFragment() {

    private val mFileDownloader by lazy {
        FileDownloader()
    }

    private var mDiskLruCache: DiskLruCache? = null

    override val layoutId = R.layout.frag_pdf_view

    override fun initView(savedInstanceState: Bundle?) {
        pbLoading.visibility = View.VISIBLE
    }

    override fun initData() {
        super.initData()
        mDiskLruCache =
            DiskLruCache.open(getDir(), 1, 1, 100 * 1024 * 1024)


     /*   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val permissions = arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            requestPermissions(permissions,RequestCode_PdfViewFragment )
        }*/

        arguments?.getString(PDF_URL)?.run {
            showPdfView(this)
        }

//        showPdfView("https://test-icloudeep-img.oss-cn-beijing.aliyuncs.com/module/uploads/JS331083210325114220715200_73879.pdf")
    }

    private fun getDir() =
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) context?.getExternalFilesDir(
            "contracts"
        )
        else context?.cacheDir

    override fun onDestroyView() {
        super.onDestroyView()
        mFileDownloader.cancel()
        mDiskLruCache?.close()
    }

    protected fun showPdfView(url: String?) {

        if (url == null) {
            emptyView.visibility = View.VISIBLE
            pbLoading.visibility = View.GONE
            return
        }

        val key = MD5Util.md5(url)
       // logi { "url = $url, key = $key" }
        if (key == null) {
            showErrorView()
            return
        }

        val snapshot = mDiskLruCache?.get(key)
        if (snapshot != null) {
            val inputStream = snapshot.getInputStream(0)
            outputStreamIntoPdfView(inputStream, key)
          //  logi { "从本地缓存中获取pdf" }
        } else {
            downloadPdf(url, key)
           // logi { "从网络上下载pdf" }
        }
    }

    private fun outputStreamIntoPdfView(inputStream: InputStream?, key: String?) {
        if (pbLoading == null) {
            return
        }
        pbLoading.visibility = View.GONE
        try {
            pdfView.visibility = View.VISIBLE
            pdfView.fromStream(inputStream)
                .enableSwipe(true)
                .swipeHorizontal(false)
                .enableDoubletap(true)
                .defaultPage(0)
                .enableAnnotationRendering(true)
                .password(null)
                .scrollHandle(null)
                .enableAntialiasing(true)
                .spacing(0)
                .load()
        } catch (e: Exception) {
           // logi { "exception : $e" }
            errorView.visibility = View.VISIBLE
            mDiskLruCache?.remove(key)
        }
    }


    private fun downloadPdf(url: String, key: String) {

        val editor = mDiskLruCache?.edit(key)
        mFileDownloader.download(url, editor?.newOutputStream(0), object : DownloadCallBack {
            override fun onComplete(filename: String?) {
                editor?.commit()
                activity?.runOnUiThread {
                    outputStreamIntoPdfView(mDiskLruCache?.edit(key)?.newInputStream(0), key)
                }
            }

            override fun onError(t: Throwable?) {
                val closed = mDiskLruCache?.isClosed
                if (closed != null && !closed) {
                    mDiskLruCache?.edit(key)?.abort()
                }
                activity?.runOnUiThread {
                    showErrorView()
                }
            }

            override fun onProgress(filename: String?, percent: Int) {

            }
        })
    }

    protected fun showErrorView() {
        pbLoading?.visibility = View.GONE
        errorView?.visibility = View.VISIBLE
    }

    companion object {

        private const val PDF_URL = "pdfUrl"

        fun newInstance(pdfUrl: String): PdfViewFragment {
            return PdfViewFragment().apply {
                arguments = Bundle().apply {
                    putString(PDF_URL, pdfUrl)
                }
            }
        }
    }
}